/********************************************************************************
 * @Author: Zhenzhou Liu
 * @Date: 2024-12-29
 * @Description: Cg贪心练习之树的最小带权路径长度
 *******************************************************************************/
#include<iostream>
#include<vector>
#include<queue>

using namespace std;

struct HuffmanNode {
    int weight;
    HuffmanNode *left;
    HuffmanNode *right;

    HuffmanNode(int w, HuffmanNode *l, HuffmanNode *r) : weight(w), left(l), right(r) {}

    HuffmanNode(int w) {
        this->weight = w;
        this->left = nullptr;
        this->right = nullptr;
    }
};

struct Compare {
    bool operator()(const HuffmanNode *a, const HuffmanNode *b) {
        return a->weight > b->weight;
    }
};

int minWPL(const vector<int> & weights) {
    priority_queue<HuffmanNode *, vector<HuffmanNode *>, Compare> pq;
    for (size_t i = 0; i < weights.size(); i++) {
        pq.push(new HuffmanNode(weights[i]));
    }

    while (pq.size() > 1) {
        HuffmanNode *left = pq.top();
        pq.pop();
        HuffmanNode *right = pq.top();
        pq.pop();
        pq.push(new HuffmanNode(left->weight + right->weight, left, right));
    }

    queue<pair<HuffmanNode *, int>> que;
    que.emplace(pq.top(), 0);
    int wpl = 0;
    while (!que.empty()) {
        HuffmanNode *node = que.front().first;
        int depth = que.front().second;
        que.pop();
        if (node->left == nullptr && node->right == nullptr){
            wpl += node->weight * depth;
            delete node;
        } else {
            if (node->left != nullptr)
                que.emplace(node->left, depth + 1);
            if (node->right != nullptr)
                que.emplace(node->right, depth + 1);
        }
    }
    return wpl;
}

int main() {
    int n;
    cin >> n;
    vector<int> weights(n);
    for (int i = 0; i < n; i++) {
        cin >> weights[i];
    }

    cout << minWPL(weights);
    return 0;
}

/*Test Case
4
2 5 3 4
*/
